package restaurant.behaviours.master;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.Hashtable;
import java.util.Iterator;
import java.util.ListIterator;

import restaurant.agents.MasterWaiterAgent;
import restaurant.core.CustomizedPerformative;
import restaurant.core.Request;

public class MasterReadyBehaviour extends CyclicBehaviour {
	
	private static final long serialVersionUID = 7779589899153995146L;
	private MasterWaiterAgent agent;
	
	public MasterReadyBehaviour(MasterWaiterAgent agent) {
		this.agent = agent;
	}

	@Override
	public void action() {
		if(this.agent.restaurant.readyMeals.isEmpty())
			return;
		
		if(this.agent.freeWaiters.isEmpty())
			return;

		synchronized (this.agent.restaurant.readyMeals) {
			ListIterator<Hashtable<Request, Boolean>> iterator = this.agent.restaurant.readyMeals.listIterator();
			while(iterator.hasNext()) {
				Hashtable<Request, Boolean> hash = iterator.next();
				Request r = hash.keys().nextElement();
				if(!hash.get(r)) {
					for (Iterator<AID> waiter = this.agent.freeWaiters.keySet().iterator(); waiter.hasNext();) {
						AID tmp = waiter.next();
						if(this.agent.freeWaiters.get(tmp)) {
							hash.put(r, true);
							this.agent.freeWaiters.put(tmp, false);
							ACLMessage message = new ACLMessage(CustomizedPerformative.AVAILABLE_WAITER);
							message.setContent("" + CustomizedPerformative.WAITER_KITCHEN_COMMUNICATION);
							message.addReceiver(tmp);
							myAgent.send(message);
							return;
						}
					}
				}
			}
		}
	}

}